import React from "react";
import {inject, observer} from 'mobx-react';
import { toJS } from 'mobx';
import {  WeaTop,WeaLocaleProvider,WeaButton,WeaSelect,WeaRightMenu} from 'ecCom';

import {Row,Button,Spin,Tooltip} from 'antd';
import { filterBR } from '../util/util';
import DatePicker from './myWorkPlan/rightContainer/rightTab/datePicker/DatePicker';
import WorkPlanCreate from '../public/workPlanCreate/index';

import moment from 'moment';

const getLabel = WeaLocaleProvider.getLabel;
const i18n=window.workplanCalendarI18n;
@inject('myWorkPlanStore')
@observer
class OneWeekWorkplan extends React.Component {
    constructor(props) {
        super(props);
        this.state = { 
          iconVisible: false,
        };
    }

    componentDidMount() {
      const { doInit,oneWeekStatus,getWorkPlanWeekGroupSelect,getWorkPlanWeekData } = this.props.myWorkPlanStore;
      const { selectedVal,isIcon1 } = oneWeekStatus;
      // doInit('', 'isInit');
      getWorkPlanWeekGroupSelect('',getWorkPlanWeekData); // 选择框
    }

    componentWillReceiveProps(nextProps) {
      if(nextProps.location && this.props.location.key !== nextProps.location.key) {
        this.doRefresh();
      }
    }

    componentDidUpdate() {
      const { setParams } = this.props.myWorkPlanStore;
      let workplanContentDisplay = this.refs.workplanContentDisplay;
      setParams({workplanContentDisplayWidth: workplanContentDisplay.offsetWidth});
      this.setHrminfoText(); // js处理超出两行点点
    }

    componentWillUnmount() {
      const { setOneWeekParams, setStatusParams, setParams } = this.props.myWorkPlanStore; 
      // 清空数据
      setOneWeekParams({dateStr: ''});
      setStatusParams({date: new Date()});
      setParams({exportExcelUrl: ''});// 解决切换页面重复下载附件的问题
    }

    setHrminfoText = () => {
      const infoHrmText = document.getElementsByClassName('info-hrm');
      for(let i in infoHrmText) {
        if(i === 'length') break;
        let text = infoHrmText[i].innerHTML;
        let height = infoHrmText[i].clientHeight;
        if(height > 38) {
          // infoHrmText[i].style.border = '1px solid red';
          let node = '';
          let nextText = '';
          for(let j=0; height > 38; j++) {
            node = document.getElementsByClassName('info-hrm')[i];
            nextText = node.innerHTML;
            if(nextText.length > 200) {
              node.innerHTML = nextText.substring(0,200)
            }else{
              node.innerHTML = nextText.substring(0, nextText.length-1);
            }
            height = node.clientHeight;
          }
          node.innerHTML = nextText.substring(0, nextText.length-5) + '...';
        }
      }
    }

    getBreadcrumb = ()=>{
        let {status,changeSelectedUser,doUpdateCalender} = this.props.myWorkPlanStore
        let {selectedUser,selectedUserName,workPlanShow} = toJS(status)
        let breadcrumb = [
            {
                name:  getLabel(503461,'一周日程安排'),
                onClick: () => {changeSelectedUser('','');selectedUser=='' && doUpdateCalender(true)},
            },
        ];
        return breadcrumb 
    }

    datePickerOnchange = (momentValue,value)=>{
      const {getWorkPlanWeekData,oneWeekStatus,setOneWeekParams} = this.props.myWorkPlanStore;
      const {selectedVal} = oneWeekStatus;
      let copyMoment = '',copyDate ='';
      if(momentValue._isAMomentObject){
        let copy = moment(momentValue);
        copyDate = copy.format("YYYY-MM-DD")
      }
      setOneWeekParams({dateStr: copyDate});
      getWorkPlanWeekData({selectDate: copyDate,groupId: selectedVal}); // 获取周列表信息
      if(typeof(value) === 'string'){
        this.props.myWorkPlanStore.changeOptions(value,'oneweek',momentValue);
      }else{
        this.props.myWorkPlanStore.changeOptions(copyDate,'oneweek',momentValue);
      }
    }

    doRefresh = ()=>{
        let {status,doUpdateCalender,changeGetCalendarData,getWorkPlanWeekData,oneWeekStatus} = this.props.myWorkPlanStore
        let {workPlanShow,date} = toJS(status);
        const {selectedVal,dateStr} = oneWeekStatus;
        workPlanShow == 'calender' && doUpdateCalender(true);
        workPlanShow == 'list' && changeGetCalendarData();
        getWorkPlanWeekData({selectDate: dateStr,groupId: selectedVal});// 获取周列表信息
    }

    doSerch = ()=>{
      let {status,getRightMenu,onRightMenuClick,changeTimeType,search,getWorkPlanWeekData,oneWeekStatus,setOneWeekParams} = this.props.myWorkPlanStore
      const {selectedVal} = oneWeekStatus;
      search()
      setOneWeekParams({dateStr: moment(new Date()).format("YYYY-MM-DD")});
      getWorkPlanWeekData({groupId: selectedVal});// 获取周列表信息
    }

    getTableHeaderInfo = (date) => {
        let { oneWeekStatus } = this.props.myWorkPlanStore
        let { weekstartday } = toJS(oneWeekStatus);
        let blockNum = 0, tableTitle = '', tableHeaders = [];
        let dateCopyMoment = moment(date);
        let weekday = new Array(7)
        weekday[0] = getLabel(398,'星期日') //getLabel(16106,'周日')
        weekday[1] = getLabel(392,'星期一')//getLabel(16100,'周一')
        weekday[2] = getLabel(393,'星期二')//getLabel(16101,'周二')
        weekday[3] = getLabel(394,'星期三')//getLabel(16102,'周三')
        weekday[4] = getLabel(395,'星期四')//getLabel(16103,'周四')
        weekday[5] = getLabel(396,'星期五')//getLabel(16104,'周五')
        weekday[6] = getLabel(397,'星期六')//getLabel(16105,'周六')
    
        for (var i = 0; i < 7; i++) {
          let dayMoment='';
          let obj = {};
          if (weekstartday == '0') {
            dayMoment=dateCopyMoment.day(i);
          } else if (weekstartday == '1' && dateCopyMoment.day() > 0) {
            dayMoment=dateCopyMoment.day(i+1);
          } else if (weekstartday == '1' && dateCopyMoment.day() == 0) {
            dayMoment=dateCopyMoment.day(i-7+1);
          }
          obj.dateStr = dayMoment.format(i18n.moment.dateformat.fulldayvalue);
          obj.weekStr = weekday[dayMoment.day()];
          tableHeaders.push(obj);
        }
        
        return { blockNum: 7, tableTitle: tableTitle, tableHeaders: tableHeaders };
    }

    getWeekRowView = () => {
      let group = [];
      let fields = [];
      let {status,workplanContentDisplayWidth,oneWeekStatus} = this.props.myWorkPlanStore;
      const {dateMoment} = toJS(status)
      const {DatasList,showNight,hasDatas,showNoon} = toJS(oneWeekStatus);
      let { blockNum, tableTitle, tableHeaders } = this.getTableHeaderInfo(dateMoment);
      let workplanContentDisplay = this.refs.workplanContentDisplay;
      fields.push(
        <div className='workplan-content-display-header' style={{width: workplanContentDisplayWidth===0 ? '100%' : workplanContentDisplayWidth}}>
          <div className='workplan-content-display-header-left' /*style={{width: hasDatas ?'calc(20% + 100px)':'calc(20% + 100px)'}}*/>{ getLabel('19736','时间') }</div>
          <div className='workplan-content-display-header-right'>{ getLabel(17795,'工作内容')}</div>
        </div>
      )
      fields.push(
          <table className="workplan-content-display-container" ref='workplanContainer' style={{height: 'calc(100% - 45px)',width: '100%',display: 'block',overflowY: 'auto'}}>
            <tbody>
                {tableHeaders && tableHeaders.length > 0 && (
                <div className='workplanContentDisplay' ref='workplanContentDisplay'>
                    {tableHeaders.map((obj,index) => {
                    return (
                        <tr>
                            <td className='workplan-week-left'>
                              <div>
                                <span>{obj.dateStr}</span>
                                <span className='week'>{obj.weekStr}</span>
                              </div>
                            </td>
                            <td className='workplan-week-right'>
                                <div className='workplan-item'>
                                  <div className='time-label'><span className="time-label-span">{getLabel(16689,'上午')}</span></div>
                                  <div className='workplan-info'>
                                    {DatasList&&DatasList[index] && DatasList[index].am && this.getWorkplanItem(DatasList[index].am)}
                                  </div>
                                </div>
                                {showNoon && <div className='workplan-item'>
                                  <div className='time-label'><span className="time-label-span">{getLabel('389284','中午') }</span></div>
                                  <div className='workplan-info'>
                                    {DatasList&&DatasList[index] && DatasList[index].noon && this.getWorkplanItem(DatasList[index].noon)}
                                  </div>
                                </div>}
                                <div className='workplan-item'>
                                  <div className='time-label'><span className="time-label-span">{getLabel(16690,'下午')}</span></div>
                                  <div className='workplan-info'>
                                    {DatasList&&DatasList[index] && DatasList[index].pm && this.getWorkplanItem(DatasList[index].pm)}
                                  </div>
                                </div>
                                {showNight && <div className='workplan-item'>
                                  <div className='time-label'><span className="time-label-span">{ getLabel(503462,'晚上')}</span></div>
                                  <div className='workplan-info'>
                                    {DatasList&&DatasList[index] && DatasList[index].night && this.getWorkplanItem(DatasList[index].night)}
                                  </div>
                                </div>}
                            </td>
                        </tr>);
                    })}
                </div>
                )}
            </tbody>
        </table>
      );
      group.push(
        <div className='workplan-content-display-row' >
          {fields}
        </div>
      );
      return group;
    }

    getWorkplanItem = (arr) => {
      const {setStatusParams} = this.props.myWorkPlanStore;
      let fields = [];
      arr && arr.map(res => {
        res.title = filterBR(res.title);
        fields.push(
          <div className='info-dispaly'>
            <div className='info-header'><label>{res.beginTime}</label>
              <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@wz76aw@${res.workid}`} placement="bottomLeft" title={<div style={{ wordBreak: 'break-all' }} dangerouslySetInnerHTML={{__html: res.title}}/>}><div ref='title' className='title' onClick={() => {setStatusParams({createType: 'preview',createVisible: true,workPlanId: res.workid})}}>{<div className='title-html' dangerouslySetInnerHTML={{__html: res.title}}/>}</div>
              </Tooltip>
            </div>
            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@9ug5v4@${res.workid}`} overlayClassName={'meeting-tooltip'} placement="bottomLeft" title={res.resourceName}>
              <div className='info-hrm' id='infoHrmText' ref='infoHrmText'>{res.resourceName}</div>
            </Tooltip>
          </div>
        )
      })

      return fields;
    }

    getWorkplanView = (workplanid) => {
      let { status, getRightMenu, onRightMenuClick, close, onlyClose, importVisible, closeImport,setDialogHeight,oneWeekStatus, getWorkPlanWeekData} = this.props.myWorkPlanStore;
      const { activeKey, selectedUser, createVisible, createType, workPlanId, createConditionParams, spinning } = toJS(status);
      const {selectedVal,dateStr} = toJS(oneWeekStatus);
      return (
        <WorkPlanCreate ecId={`${this && this.props && this.props.ecId || ''}_WorkPlanCreate@qk67vl`}
						type={createType}//新建为'create',查看为'preview',编辑edit,共享share
						visible={createVisible}//显隐受控
						doClose={this.workPlanCreateClose}//关闭回调, 保存等按钮会自动调用该回调，可以在这里写一些页面的刷新操作
						onlyClose={this.workPlanCreateOnlyClose}//关闭回调,关闭/取消等按钮会自动调用该回调，只做关闭操作
						workPlanId={workPlanId} //日程id，查看日程时用到
						createConditionParams={this.getcreateConditionParams()}//创建的默认值日期和时间,没有传[]
						activeKey={activeKey} //查看页面显示的面板1是基本信息，7是相关交流
						changeTab={this.getchangeTab}//查看页面切换面板的回调
						selectUser={selectedUser}//新建日程的接收人id
						workPlanTypeOptions=''//客户模块的新建日程，普通新建传'',客户新建传3
						crmIDs={''}//通过客户模块新建日程，并自动带出相关客户,[{'id':'','name':''}]
						crmid={''}
						docid={''}
						projectid={''}
						taskid={''}
						requestid={''}
						resourceid={''}
            description=''//客户模块需求，支持新建时传入的'基本信息-内容'
            changeOneWeekDatas={this.getchangeOneWeekDatas} // 删除或编辑刷新一周安排数据
				/>
      );
    }

    getchangeOneWeekDatas = () => {
      let { oneWeekStatus, getWorkPlanWeekData } = this.props.myWorkPlanStore;
      const {selectedVal,dateStr} = toJS(oneWeekStatus);
      getWorkPlanWeekData({selectDate: dateStr,groupId: selectedVal});
    }

    getchangeTab = (e) => {
      this.props.myWorkPlanStore.changeTab(e)
    }

    getcreateConditionParams = () => {
      return this.props.myWorkPlanStore && this.props.myWorkPlanStore.status && this.props.myWorkPlanStore.status.createConditionParams;
    }

    workPlanCreateClose = () => {
      let { close  } = this.props.myWorkPlanStore;
      close();
    }
  
    workPlanCreateOnlyClose = () => {
      let { onlyClose } = this.props.myWorkPlanStore;
      onlyClose();
    }

    getWeekCloumnView = () => {
      let {am, noon, pm, night} = this.props;
      let group = [];
      let fields = [];
      let {status,workplanContentDisplayWidth,oneWeekStatus} = this.props.myWorkPlanStore;
      const {dateMoment} = toJS(status);
      let {DatasList,showNight,showNoon} = toJS(oneWeekStatus);
      let share = 2;
      showNight && share ++;
      showNoon && share ++;
      let cloumnWid = `${100/share}%`;
      let { blockNum, tableTitle, tableHeaders } = this.getTableHeaderInfo(dateMoment);
    
      fields.push(
          <tr className='workplan-content-display-header' style={{width:  workplanContentDisplayWidth===0 ? '100%' : workplanContentDisplayWidth}}>
            <td className='workplan-content-display-header-left'></td>
            <td className='workplan-content-display-header-right'>
              <div className={`${am} time-label`} style={{width: cloumnWid}}><span>{getLabel(16689,'上午')}</span></div>
              {showNoon && <div className={`${noon} time-label`} style={{width: cloumnWid}}><span>{getLabel('389284','中午') }</span></div>}
              <div className={`${pm} time-label`} style={{width: cloumnWid}}><span>{getLabel(16690,'下午')}</span></div>
              {showNight && <div className={`${night} time-label`} style={{width: cloumnWid}}><span>{ getLabel(503462,'晚上')}</span></div>}
            </td>
          </tr>
      )
      fields.push(
          <table className="workplan-content-display-container" ref='workplanContainer'  style={{height: 'calc(100% - 45px)',width: '100%',display: 'block',overflowY: 'auto'}}>
            <tbody>
                {tableHeaders && tableHeaders.length > 0 && (
                <div className='workplanContentDisplay' ref='workplanContentDisplay'>
                    {tableHeaders.map((obj, index) => { 
           
                    return (
                        <tr>
                            <td className='workplan-week-left'>
                              <div>
                                <span>{obj.dateStr}</span>
                                <span className='week'>{obj.weekStr}</span>
                              </div>
                            </td>
                            <td className='workplan-week-right'>
                                <div className={`${am} workplan-item`} style={{width: cloumnWid}}>
                                  <div className='workplan-info'>
                                    {DatasList&&DatasList[index] && DatasList[index].am && this.getWorkplanItem(DatasList[index].am)}
                                  </div>
                                </div>
                                {showNoon && <div className={`${noon} workplan-item`} style={{width: cloumnWid}}>
                                  <div className='workplan-info noon'>
                                    {DatasList&&DatasList[index] && DatasList[index].noon && this.getWorkplanItem(DatasList[index].noon)}
                                  </div>
                                </div>}
                                <div className={`${pm} workplan-item`} style={{width: cloumnWid}}>
                                  <div className='workplan-info'>
                                    {DatasList&&DatasList[index] && DatasList[index].pm && this.getWorkplanItem(DatasList[index].pm)}
                                  </div>
                                </div>
                                {showNight && <div className={`${night} workplan-item`} style={{width: cloumnWid}}>
                                  <div className='workplan-info night'>
                                    {DatasList&&DatasList[index] && DatasList[index].night && this.getWorkplanItem(DatasList[index].night)}
                                  </div>
                                </div>}
                            </td>
                        </tr>);
                    })}
                </div>
                )}
            </tbody>
        </table>
      );
      group.push(
        <div className='workplan-content-display-column' >
          {fields}
        </div>
      );
      return group;
    }

    changeDispalyView = () => {
      let fields = [];
      const {iconVisible,} = this.state;
      const {oneWeekStatus,setOneWeekParams} = this.props.myWorkPlanStore;
      const {isIcon1,} = toJS(oneWeekStatus);
      fields.push(
        <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@ofrp92@changeDispalyView`} placement="bottom" title={''}>
        <div className='changeDispalyView' title={''} style={{boxShadow: iconVisible ? '0px 0px 10px 1px #888' : ''}} >
          <div className={iconVisible ? 'icon iconhover' :'icon'} style={{border: iconVisible ? 'none' : ''}}  onClick={() => {this.setState({iconVisible: !iconVisible});return false;}}>
            <span className='span1'><img className='span1' src={(isIcon1 === '1'||isIcon1 === 1)?require('../util/view1.png'):require('../util/view2.png')}></img></span>
            <span className='span1 icon-coms-organization-down'></span>
          </div>  
          {iconVisible && <div className={iconVisible ? 'icon iconhover' :'icon'}  style={{border: 'none'}} onClick={() => {this.updateWeekViewType()}} >
            <span className='span1'><img className='span1' src={(isIcon1 === '1'||isIcon1 === 1)?require('../util/view2.png'):require('../util/view1.png')}></img></span>
          </div>}  
        </div>
        </Tooltip>
      );
      return fields;
    }

    updateWeekViewType = () => {
      const {oneWeekStatus,setOneWeekParams,updateWeekViewType} = this.props.myWorkPlanStore;
      const {iconVisible,} = this.state;
      const {isIcon1,} = toJS(oneWeekStatus);
      this.setState({iconVisible: !iconVisible,});
      let icontype =  (isIcon1 === '1'||isIcon1 === 1)? '2' : '1';
      setOneWeekParams({isIcon1: icontype});
      updateWeekViewType({viewType: icontype});
      return false;
    }

    closeMask = (e) => {
      let classname = e.target.className;
      if(!(classname.indexOf('changeDispalyView')>-1 || classname.indexOf('icon')>-1 ||classname.indexOf('span1')>-1)) {
        this.setState({iconVisible: false});
      }
    }

    onChangeValue = (val) => {
      const {setOneWeekParams,getWorkPlanWeekData,oneWeekStatus} = this.props.myWorkPlanStore;
      const {dateStr} = oneWeekStatus;
      setOneWeekParams({selectedVal: val});
      getWorkPlanWeekData({selectDate: dateStr,groupId: val}); // 获取周列表信息
    }
    render() {
   
        let {status,open,importVisible,closeImport,exportExcelUrl,exportExcel,setDialogHeight,scrollVisible,oneWeekStatus} = this.props.myWorkPlanStore;
        const {loading,timeType,date,createVisible,createType,createConditionParams,selectedUser,activeKey,spinning,workPlanShow,dateMoment} = toJS(status)
        const {selectedOptions,selectedVal,isIcon1,weekstartday} = oneWeekStatus;
        let btns = [
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5iia7g@exportExcelOneweek`} type="primary" disabled={false} onClick={() => exportExcel('oneweek')}>{getLabel(28343,'导出Excel')}</Button>	
        ];
        let buttonsCreate = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rmje7g@doSave`} type="primary" disabled={false} onClick={()=>{this.refs.customWorkPlanCreate.refs.workPlanCreate.returnValues()}}>{getLabel(30986,'保存')}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gxo0hl@doClose`} type="primary" disabled={false} onClick={()=>{this.refs.customWorkPlanCreate.doClose()}}>{getLabel(309,'关闭')}</Button>),
        ];
     
        let breadcrumb = this.getBreadcrumb()
        const dropMenuDatas = [
          {
            key: '1',
            disabled: false,
            icon: <i className='icon-coms-download' />,
            content: getLabel(28343,'导出Excel'),
            onClick: () => exportExcel('oneweek')
          },
        ];
        // let typeOptions = [{key: '1', showname: `${getLabel(27511,'部门')}`},{key: '2', showname: `${getLabel(33553,'分部')}`},{key: '3', showname: `${getLabel(179,'人力资源')}`},]
        return (
          <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@j6mwvp`} 
            datas={dropMenuDatas}
            collectParams={{
            favname: getLabel(384890,'导入日程'),
            favouritetype: 2,
            objid: 0,
            importantlevel: 1,
            }}
          >
            <div className='one-week-workplan' onClick={(e) => {this.state.iconVisible ? this.closeMask(e) : ''}}>
              <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@nckjk9`} 
	            	loading={spinning} 
	            	icon={<i className='icon-coms-schedule' />} 
	            	iconBgcolor='#7734FF' 
	            	title={getLabel(503461,'一周日程安排')}  
	            	buttons={btns}
		            showDropIcon={true}
                dropMenuDatas={dropMenuDatas}
                // onDropMenuClick={onRightMenuClick()}
                // breadcrumb={breadcrumb}
	            	>
               
                {/* icon-coms-Tile */}
                  <div className="myWorkplan-right-tab" >
                      <DatePicker ecId={`${this && this.props && this.props.ecId || ''}_DatePicker@7fx5g4`} type={'week'} className="picker" date={date} weekstartday={weekstartday} onChange={this.datePickerOnchange} ref="workplan-tab-picker"/>
                      {<WeaButton ecId={`${this && this.props && this.props.ecId || ''}_WeaButton@7kjs4g`} type="ghost" style={{}} text={getLabel(15539,'本周')} disabled={false} onClick={this.doSerch} /> }
                      <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@uxgqr5`} placement="bottom" title={getLabel(354,'刷新')}>
                          <span className="icon-coms-Refresh" style={{cursor:'pointer',padding:'0 10px',color:'#B2B2B2',fontSize:'16px',display:'inline-block',verticalAlign:'middle'}} onClick = {this.doRefresh}></span>
                      </Tooltip>
                      {<WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@xk2wvx`} style={{width:'150px'}}  options={toJS(selectedOptions)} value={selectedVal} onChange={(value)=>{this.onChangeValue(value)}}/>}
                      {this.changeDispalyView()}
                  </div>
                  
                  {(isIcon1 === '1'||isIcon1 === 1) ? this.getWeekCloumnView() : this.getWeekRowView()}
                  {this.getWorkplanView()}
	            </WeaTop>
              <iframe name="exportExcel" src={exportExcelUrl} style={{display:'none'}}></iframe> 
            </div>
            </WeaRightMenu>
        )
    }
}

export default OneWeekWorkplan;